package com.kungfuhacking.wristbandpro.login.presenter;

import android.os.Bundle;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.kungfuhacking.wristbandpro.base.bean.Basebean;
import com.kungfuhacking.wristbandpro.base.bean.RequestBean;
import com.kungfuhacking.wristbandpro.base.presenter.BasePresenter;
import com.kungfuhacking.wristbandpro.login.activity.LoginActivity;
import com.kungfuhacking.wristbandpro.login.bean.LoginBean;
import com.kungfuhacking.wristbandpro.login.view.IForgetView;
import com.kungfuhacking.wristbandpro.login.activity.ResetPasswordActivity;
import com.kungfuhacking.wristbandpro.net.BaseNoTObserver;
import com.kungfuhacking.wristbandpro.net.RetrofitHttpUtil;
import com.kungfuhacking.wristbandpro.utils.Constant;
import com.kungfuhacking.wristbandpro.utils.LogUtil;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


/**
 * 忘记密码
 * Created by Aaron on 17/4/17.
 */

public class IForgetPresenter implements BasePresenter {

    private IForgetView iForgetView;
    private String TAG = getClass().getSimpleName();

    public IForgetPresenter(IForgetView iForgetView) {
        this.iForgetView = iForgetView;
    }

    public void getSmsCode() {

        if (TextUtils.isEmpty(iForgetView.getPhoneNum()) || iForgetView.getPhoneNum().length() != 11) {
            iForgetView.showErr("请输入正确的手机号");
            return;
        }

        JSONObject j = new JSONObject();
        j.put("phoneNum", iForgetView.getPhoneNum());
        j.put("token", iForgetView.getToken());
        j.put("type", Constant.GET_SMS_CODE_FORGET);

        RetrofitHttpUtil.getInstance().getSms(new BaseNoTObserver<Basebean>() {

            @Override
            public void onSubscribe(Disposable d) {
                compositeDisposable.add(d);
                iForgetView.showLoading("获取中...");
            }

            @Override
            public void onHandleSuccess(Basebean basebean) {
                iForgetView.hideLoading();
                iForgetView.showErr("请注意查收验证码");
                countDown();//倒计时
            }

            @Override
            public void onHandleError(String message) {
                iForgetView.hideLoading();
                iForgetView.showErr(message);
            }

            @Override
            public void onReLogin(String message) {
                iForgetView.showErr(message);
                iForgetView.hideLoading();
                iForgetView.nextActivityWithSingleTask(LoginActivity.class);
            }
        }, new RequestBean().setData(j.toString()));

    }

    private Disposable countDisposable;
    private final int TIME = 60;

    /**
     * 倒计时
     */
    private void countDown() {

        iForgetView.setUnclickable();//设置控件不可点击

        Observable.interval(0, 1, TimeUnit.SECONDS, AndroidSchedulers.mainThread()).map(new Function<Long, String>() {
            @Override
            public String apply(Long aLong) throws Exception {

//                LogUtil.d(TAG, "发送事件 " + aLong);

                if (aLong > TIME)
                    countDisposable.dispose();

                if (aLong == TIME) {
                    iForgetView.setClickable();//设置控件可以点击
                    return "获取验证码";
                }

                return (TIME - aLong) + " 秒";
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        countDisposable = d;
                    }

                    @Override
                    public void onNext(String value) {
//                        LogUtil.d(TAG, "接受事件:" + value);
                        iForgetView.setCountTime(value);
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtil.d(TAG, "事件错误" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    public void nextStep() {

        if (TextUtils.isEmpty(iForgetView.getPhoneNum()) || iForgetView.getPhoneNum().length() != 11) {
            iForgetView.showErr("请输入正确的手机号");
            return;
        }

        if (TextUtils.isEmpty(iForgetView.getCode())) {
            iForgetView.showErr("请输入验证码");
            return;
        }

        submitConfirm();//提交验证
    }

    private void submitConfirm() {

        JSONObject j = new JSONObject();

        j.put("phoneNum", iForgetView.getPhoneNum());
        j.put("msCode", iForgetView.getCode());

        RetrofitHttpUtil
                .getInstance()
                .forgetCheckCode(
                        new BaseNoTObserver<LoginBean>() {
                            @Override
                            public void onHandleSuccess(LoginBean tokenEntry) {
                                iForgetView.hideLoading();
                                Bundle bundle = new Bundle();
                                bundle.putString("token", tokenEntry.getToken().getToken());
                                LogUtil.e(TAG, "token : " + tokenEntry.getToken().getToken());
                                iForgetView.nextActivityWithBundle(ResetPasswordActivity.class, bundle);
                            }

                            @Override
                            public void onHandleError(String message) {
                                iForgetView.hideLoading();
                                iForgetView.showErr(message);
                            }

                            @Override
                            public void onReLogin(String message) {
                                iForgetView.showErr(message);
                                iForgetView.hideLoading();
                                iForgetView.nextActivityWithSingleTask(LoginActivity.class);
                            }

                            @Override
                            public void onSubscribe(Disposable d) {
                                compositeDisposable.add(d);
                                iForgetView.showLoading("验证中...");
                            }
                        }
                        , new RequestBean().setData(j.toString()));

    }

    @Override
    public void clearRequest() {
        compositeDisposable.clear();
        if (countDisposable != null)
            countDisposable.dispose();
    }
}
